//
//  EvaluateViewController.swift
//  OnceNectar
//
//  Created by 法正磊 on 2018/2/25.
//  Copyright © 2018年 com.inwhoop. All rights reserved.
//

import UIKit
import SwiftyJSON
import IQKeyboardManagerSwift
import Networking
import Alamofire
import PKHUD

class EvaluateViewController: BaseViewController,UITableViewDelegate,UITableViewDataSource,EvaluateTableViewCellDelegate{
    
    @IBOutlet weak var tableView: UITableView!
    var model:myOrderModel?
    var selectCell:EvaluateTableViewCell?
    var result = [EvaluateModel]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        
    }
    
    private func setUI() {
        for item in (model?.purchaseGoodsInfos)! {
            var comment:EvaluateModel = EvaluateModel()
            comment.predictabilityGrade = "5"
            comment.beautyGrade = "5"
            comment.costGrade = "5"
            comment.jointId = ""
            comment.imgArr = []
            comment.imgIds = []
            comment.goodId = item.goodsId
            comment.orderId = model?.id
            result.append(comment)
        }
        titleLabel(text: "评价", nil)
        tableView.register(UINib(nibName: "\(EvaluateTableViewCell.self)", bundle: nil), forCellReuseIdentifier: "cell")
        tableView.reloadData()
    }
    
    
    
    override func setNavigation() {
        let button = UIButton(type: .custom)
        button.setTitle("提交", for: .normal)
        button.setTitleColor(UIColor.white, for: .normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        button.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
        button.addTarget(self, action: #selector(submit), for: .touchUpInside)
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button)
    }
    
    func updateDate(model: EvaluateModel, index: Int) {
        self.result[index] = model
    }
    
    
    @objc func submit() -> Void {
        let count:Int = result.count - 1
        for i in 0...count {
            let data:EvaluateModel = result[i]
            if data.commentContent == "" {
                self.showToast(msg: "请输入评论内容")
                self.tableView.scrollToRow(at: IndexPath.init(row: 0, section: i), at: UITableViewScrollPosition.top, animated: true)
                return
            }
        }
        var datatr:String = String.init("[")
        var c:Int = 0
        for item in result {
            let orderId:String = item.orderId!
            let goodId:String = item.goodId!
            var jointId:String = item.jointId!
            let predictabilityGrade:String = item.predictabilityGrade!
            let beautyGrade:String = item.beautyGrade!
            let costGrade:String = item.costGrade!
            let commentContent:String = item.commentContent!
            if c > 0 {
                datatr.append(",")
            }
            if jointId != "" {
                jointId = "\"jointId\":\(jointId),"
            }
            let str = "{\"orderId\":\(orderId), \"goodId\":\(goodId),\(jointId)\"predictabilityGrade\":\(predictabilityGrade),\"beautyGrade\":\(beautyGrade),\"costGrade\":\(costGrade),\"commentContent\":\(commentContent)}"
            datatr.append(str)
            c += 1
        }
        datatr.append("]")
        self.submitReq(params: ["data":datatr])
    }
    
    func submitReq(params:[String:String]) -> Void {
        let requesturl = appendUrl(suffix: commendGoodsUrl)
        Alamofire.request(requesturl, method: .post,
                          parameters: params,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        self.view.makeToast("一度蜜：" + json["message"].string!, duration: 1.5, position: .center) { (flag) in
                                                self.navigationController?.popViewController(animated: true)
                                            }
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                    else{
                                        
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                
                                self.showToast(msg:"网络错误")
                            }
                            
        }
    }
    
    // MARK: - tableViewDataSource
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return (model?.purchaseGoodsInfos?.count)!
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as? EvaluateTableViewCell
        cell?.backgroundColor = UIColor.white
        let goodsInfo = model?.purchaseGoodsInfos?[indexPath.section]
        cell?.model = goodsInfo
        cell?.setData(commentModel: result[indexPath.section])
        cell?.index = indexPath.section
        cell?.delegate = self
        return cell!
    }


}
